package com.yz.crm.passport.action;


import com.yz.common.util.JDKStackTrace;
import com.yz.crm.weixin.model.ThirdPartyUser;
import com.yz.crm.weixin.service.ThirdPartyUserService;
import com.yz.util.Constants;
import com.yz.util.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户登录时，检测用户是否登录，(如果用户未登录，但是已经存在绑定关系，)
 * * Created by DOVE on 2015/9/22.
 */
@Component
public class UserResolver {
    private static final Log log = LogFactory.getLog(UserResolver.class);

    @Resource
    private ThirdPartyUserService thirdPartyUserService;

    public void addCookie(HttpServletRequest request, HttpServletResponse response, String memberId, String openId) {
        //更新cookie
        WebUtils.addCookie(request, response, Constants.COOKIE_USER_OPENID, openId, Constants.COOKIE_MAX_AGE);
        WebUtils.addCookie(request, response, Constants.COOKIE_USER_THIRDPARTY_ID, memberId, Constants.COOKIE_MAX_AGE);
    }

    public void removeCookie(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.removeCookie(request, response, Constants.COOKIE_USER_OPENID);
        WebUtils.removeCookie(request, response, Constants.COOKIE_USER_THIRDPARTY_ID);
    }

    /**写入会话和cookie*/
    private boolean writeSessionAndCookie(HttpServletRequest request, HttpServletResponse response, HttpSession session, String openId, String userId) throws Exception {
       /* Member member = memberService.getMember(memberId);
        //用户不存在返回false
        if (member==null){
        	return false;
        }
        session.setAttribute(Constants.SESSION_KEY_MEMBER, member);
        //登录事件
        memberEventService.logon(request);
        //更新cookie
        addCookie(request, response, memberId, openId);*/
        
        return true;
    }

    //通过cookie登录
    public boolean loginByCookie(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String ip = WebUtils.getIp(request);
        String sessionId = request.getSession().getId();

        boolean isWechatRequest = WebUtils.isWeChatRequest(request);
        if (!isWechatRequest) {
            log.warn("----->>> ip=" + ip + ",sessionId=" + sessionId + ",ua=" + request.getHeader("user-agent"));
            return false;
        }
        String openId = WebUtils.getCookie(request, Constants.COOKIE_USER_OPENID);
        String userId = WebUtils.getCookie(request, Constants.COOKIE_USER_THIRDPARTY_ID);
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(openId)) {
            return false;
        }
        ThirdPartyUser baseThirdPartymember =thirdPartyUserService.getInfo (null,openId);
        if (baseThirdPartymember == null) {
            log.warn("----->>> baseThirdPartyUser=null. ip=" + ip + ",sessionId=" + sessionId
                    + ",userId=" + userId + ",openId=" + openId);
            return false;
        }
        log.info("----->>> ip=" + ip + ",sessionId=" + sessionId + ",memberId=" + userId + ",openId=" + openId);
        try {
            return writeSessionAndCookie(request, response, session, baseThirdPartymember.getOpenId(), userId);
        } catch (Exception e) {
            session.removeAttribute(Constants.SESSION_KEY_USER);
            removeCookie(request, response);
            log.warn("----->>> ip=" + sessionId + ",sessionId=" + sessionId + ",memberId=" + userId + ",openId=" + openId
                    + "写cookieSession错误" + JDKStackTrace.getJDKStrack(e));
            return false;
        }
    }
}
